/*
 * Copyright 2007-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.paoding.rose.web.impl.typeconverter;

import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 
 * @author Zhiliang Wang [qieqie.wang@gmail.com]
 * @since 0.5
 */
public class DatePropertyEditor extends PropertyEditorSupport {

	private String datePattern;
	private SimpleDateFormat dateFormat;

	private String dateTimePattern;
	private SimpleDateFormat dateTimeFormat;

	private String timePattern;
	private SimpleDateFormat timeFormat;

	private String stimePattern;
	private SimpleDateFormat stimeFormat;

	public DatePropertyEditor() {
		dateTimePattern = "yyyy-MM-dd HH:mm:ss";
		dateTimeFormat = new SimpleDateFormat(dateTimePattern);

		datePattern = "yyyy-MM-dd";
		dateFormat = new SimpleDateFormat(datePattern);

		timePattern = "HH:mm:ss";
		timeFormat = new SimpleDateFormat(timePattern);

		stimePattern = "HH:mm";
		stimeFormat = new SimpleDateFormat(stimePattern);
	}

	public void setAsText(String text) throws IllegalArgumentException {
		if (text == null || text.length() == 0) {
			setValue(null);
		}
		try {
			if (text.length() == dateTimePattern.length()) {
				setValue(dateTimeFormat.parse(text));
			} else if (text.length() == datePattern.length()) {
				setValue(dateFormat.parse(text));
			} else if (text.length() == timePattern.length()) {
				setValue(timeFormat.parse(text));
			} else if (text.length() == stimePattern.length()) {
				setValue(stimeFormat.parse(text));
			} else {
				try {
					setValue(new Date(Long.parseLong(text)));
				} catch (Exception e) {
					throw new IllegalArgumentException(
							"illegal text for date editor:" + text);
				}

			}
		} catch (IllegalArgumentException e) {
			throw e;
		} catch (Exception e) {
			throw new IllegalArgumentException(e);
		}
	}
}
